<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-form label-width="70px" size="small">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="月份">
                <el-date-picker
                  v-model="date"
                  type="month"
                  size="small"
                  class="date-item"
                  style="width: 100%"
                  format="yyyy - M"
                  value-format="yyyy-M"
                />
                <!-- <el-option
                    v-for="item in month"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value">
                  </el-option> -->
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="部门">
                <!-- <TreeSelect
                  v-model="query.deptId"
                  :options="depts"
                  placeholder="选择部门"
                  style="width:  100%"
                  :normalizer="normalizer"
                /> -->
                <zSelect
                  :value.sync="query.deptIds"
                  :showName="query.deptName"
                  url="api/dropDown/childSysDeptList"
                  @change="changeDept"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="人员">
                <zSelect
                  :value.sync="query.userIds"
                  url="api/dropDown/sysUserList"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!-- <rrOperation :crud="crud" /> -->
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          @click="queryReport"
          >搜索</el-button
        >
        <el-button
          class="filter-item"
          plain
          size="mini"
          type="primary"
          @click="resetQuery"
          >重置</el-button
        >
        <el-button
          :disabled="this.crud.selections.length !== 1"
          type="primary"
          @click="achievements"
          >计算绩效工资</el-button
        >
        <el-button
          type="primary"
          @click="calculateFinalSalary"
          :disabled="this.crud.selections.length == 0"
          >计算待发工资</el-button>
      </div>
      <crudOperation :permission="permission" >

        <el-button
          slot="right"
          :loading="crud.downloadLoading"
          class="filter-item"
          size="mini"
          type="warning"
          @click="doExport"
        >导出</el-button>
      </crudOperation>

    </div>
    <!-- 表单渲染 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="crud.status.title"
      :visible.sync="flag"
      append-to-body
      modal-append-to-body
      width="520px"
    >
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="small"
      >
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          @click="addParamsSetting"
          style="margin-bottom: 20px"
          >新增</el-button
        >
        <table cellspacing="0" border="1">
          <tr>
            <th style="width: 180px">扣减金额</th>
            <th style="width: 180px">扣减原因</th>
            <th style="width: 180px" class="bgc">操作</th>
          </tr>
          <tr
            :data="form.reduce"
            v-for="(item, index) in form.reduce"
            :key="index"
          >
            <td>
              <el-input
                class="border"
                v-model="item.deductedSalary"
                type="number"
                placeholder="请输入金额"
                required
              />
            </td>
            <td>
              <el-input
                class="border"
                v-model="item.deductedReason"
                type="text"
                placeholder="请输入扣减原因"
              />
            </td>
            <td class="bgc">
              <el-button
                class="filter-item"
                size="mini"
                type="primary"
                @click="del(index)"
                >删除</el-button
              >
            </td>
          </tr>
        </table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="flag = false">取消</el-button>
        <el-button :loading="crud.cu === 2" type="primary" @click="submit"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <div class="body-container">
      <!--表格渲染-->
      <el-table
        ref="table"
        border
        height="700"
        show-summary
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%"
        :summary-method="crud.sumRow"
        @row-click="crud.selectRow"
        :row-style="crud.rowClass"
        :row-class-name="crud.tableRowClassName"
        @selection-change="crud.selectionChangeHandler"
        @row-dblclick="jump('salarySettlementDetail', $event)"
      >
        <el-table-column
          :render-header="crud.renderHeader"
          type="selection"
          width="60"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('month')"
          prop="month"
          label="月份"
        >
          <template>
            <span>{{ query.year }}-{{ query.month }}</span>
          </template>
        </el-table-column>

        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('deptName')"
          prop="deptName"
          label="部门"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('userName')"
          prop="userName"
          label="人员"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('salaryStand')"
          prop="salaryStand"
          label="基本工资"
        />
        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('totalPerformance')"
          prop="totalPerformance"
          label="绩效工资"
        />

        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('')"
          prop=""
          label="扣减工资(可以增加条目)"
        >
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('totalDeductedSalary')"
            prop="totalDeductedSalary"
            label="扣减金额"
          >
            <template slot-scope="scope">
              <span @click.stop="DeductedSalary(scope.row)" class="blue">{{
                scope.row.totalDeductedSalary
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :render-header="crud.renderHeader"
            v-if="columns.visible('totalDeductedReason')"
            prop="totalDeductedReason"
            label="扣减原因"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.totalDeductedReason }}</span>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          :render-header="crud.renderHeader"
          v-if="columns.visible('finalSalary')"
          prop="finalSalary"
          label="待发工资"
        />
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
//   import crudBasGoods from '@/api/erp/classesIndex'
import {
  getPage,
  calculatePerformance,
  calculateFinalSalary,
  getDeductedList,
  saveOrUpdateDeduction,
  getPerformance,
} from "@/api/erp/salarySettlement";
import salarySettlement from "@/api/erp/salarySettlement";
import CRUD, { crud, form, header, presenter } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import TreeSelect from "@riophae/vue-treeselect";
import {download} from "@/api/data";
import {downloadFile} from "@/utils";
const date = new Date()
const curDate = new Date(date.getFullYear(),date.getMonth()-1,1)
const year  = curDate.getFullYear()
const month = curDate.getMonth() + 1
let thisDate = `${year}-${month}`;
// crud交由presenter持有
const defaultCrud = CRUD({
  title: "扣减",
  url: "/api/salarySettlement/getPage",
  sort: "id,desc",
  query: {
    deptIds: "",
    month,
    year,
    userIds: "",
  },
  crudMethod: { ...salarySettlement },
  optShow: {
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
  },
  props: {
    tableColumns: ["name", "code", "type", "sourceType"],
  },
});
const defaultForm = {
  thisDate: thisDate,
  busDate: null,
  deptIds: null,
  userIds: "",
  id: null,
  deptCode: "",
  deptId: 0,
  deptName: "",
  finalSalary: 0,
  month: 0,
  salaryStand: 0,
  settleTime: "",
  settleUserCode: "",
  settleUserId: 0,
  settleUserName: "",
  totalDeductedReason: [],
  totalDeductedSalary: [],
  totalPerformance: null,
  DeductedSalary: "",
  userCode: "",
  userId: 0,
  userName: "",
  year: 0,
  reduce: [],
};
export default {
  name: "salarySettlement",
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    TreeSelect,
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      flag: false,
      date: thisDate,
      multiple: true,
      depts: [],
      busDate: [],
      totalDeductedSalary: [],
      permission: {
        //add 不添加权限，这个add按钮自定义
        add: ["admin"],
        edit: ["admin", "basGoods:edit"],
        del: ["admin", "basGoods:del"],
        enable: ["admin", "basGoods:enable"],
        disable: ["admin", "basGoods:disable"],
      },
      rules: {},
      brandList: [],
      typeList: [],
      id: null,
    };
  },
  watch: {
    $route(){
      this.jump()
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  created() {},
  activated(){
  },
  methods: {
    addParamsSetting() {
      let item = {
        deductedReason: "",
        deductedSalary: "",
      };
      this.form.reduce.push(item);
    },
    del(a) {
      for (let index = 0; index < this.form.reduce.length; index++) {
        if (index == a) {
          this.form.reduce.splice(index, 1);
        }
      }
    },
    doExport(){
      this.crud.downloadLoading = true
      download('/api/salarySettlement/export', this.crud.getQueryParams(),this.crud.queryType).then(result => {
        downloadFile(result, '工资结算数据', 'xlsx')
        this.crud.downloadLoading = false
      }).catch(() => {
        this.crud.downloadLoading = false
      })
    },
    resetQuery() {
      this.date = "";
      this.crud.resetQuery();
    },
    queryReport() {
      if (!this.date) {
        this.$message("请先选择年月");
      } else {
        this.query.year = this.date.split("-")[0];
        this.query.month = this.date.split("-")[1];
        this.crud.toQuery();
      }
    },
    // 计算绩效工资
    async achievements() {
      let id = this.crud.selections.map((item) => item.id);
      let res = await calculatePerformance(id[0]);
      this.form.totalPerformance = res.data.totalPerformance;
      this.crud.refresh();
    },
    // 批量计算待发工资
    async calculateFinalSalary() {
      let idlist = this.crud.selections.map((item) => item.id);
      let res = await calculateFinalSalary(idlist);
      this.crud.refresh();
    },
    // 获取扣减列表
    async DeductedSalary(row) {
      this.form.id = row.id;
      this.form.totalDeductedSalary = row.totalDeductedSalary;
      let res = await getDeductedList(row.id);

      this.form.reduce = res.data;
      this.flag = !this.flag;
    },
    async submit() {
      const datailList = this.form.reduce.map((item) => {
        if (!item.deductedReason) {
          item.deductedReason = "无";
        }
        return {
          ...item,
          settlementId: this.form.id,
        };
      });
      let res = await saveOrUpdateDeduction({
        id: this.form.id,
        deductedDetailList: datailList,
      });

      this.form.totalDeductedSalary = res.data.totalDeductedSalary;
      this.flag = !this.flag;
      this.crud.refresh();
    },
    // 查询列表
    async getlist() {
      let res = await getPage({
        page: 1,
        size: null,
        deptIds: "",
        month: this.query.month,
        year: this.query.year,
        userIds: "",
        sort: "id,desc",
        totalDeductedSalary: this.query.totalDeductedSalary,
      });
      crud.data = res.data.content;
    },
    onTimeUp(data) {
      this.form.dataScope1 = data === "duo" ? [] : "";
      this.multiple = false;
      this.$nextTick(() => {
        this.multiple = true;
      });
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    jump(url, e) {
      this.$router.push({ path: url + "/" + e.id});
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true;
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {},
    changeDept(e) {
      const { id } = e;
      this.userParams.deptIds = id;
    },
    //添加提交
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.dataScope === "自定义" && crud.form.depts.length === 0) {
        this.$message({
          message: "自定义数据权限不能为空",
          type: "warning",
        });
        return false;
      } else if (crud.form.dataScope === "自定义") {
        const depts = [];
        crud.form.depts.forEach(function (data, index) {
          const dept = { id: data };
          depts.push(dept);
        });
        crud.form.depts = depts;
      } else {
        crud.form.depts = [];
      }
      return true;
    },
  },
};
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.blue {
  color: #409eff;
  display: inline-block;
  text-align: center;
  cursor: pointer;
}
.border {
  border: 0;
}
.bgc {
  text-align: center;
}
</style>
